#include "tcp_client.h"

#include <QThread>

TcpClient::TcpClient(QObject* object, QString ip, int port)
{

    qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");
    qDebug()<<"TcpClient::TcpClient"<< QThread::currentThread();

    m_ip = ip;
    m_port = port;
    m_object = object;

}

void TcpClient::initializeFunction()
{
    qDebug()<<"initializeFunction()"<< QThread::currentThread();

    m_tcpSocket = new QTcpSocket();


    startClientReconnectTcpServerTimer();

    m_tcpSocket->connectToHost(m_ip, m_port);

    //成功连接
    connect(m_tcpSocket, &QTcpSocket::connected, this, [=]() {

        //发送上电信息
        QByteArray data;
        data += 0x02;
        m_tcpSocket->write(data);
    });

    //断开连接
    connect(m_tcpSocket, &QTcpSocket::disconnected,
            this, [&](){
                        m_reconnectTimer->setInterval(0);
                         m_reconnectTimer->start(m_refreshTime);
            });

    //接受到服务器信息
    connect(m_tcpSocket, &QTcpSocket::readyRead, this, [&](){
        while (m_tcpSocket->bytesAvailable() > 0)
        {
            m_receiveData = m_tcpSocket->readAll();


            qDebug()<<"收到的数据:"<<m_receiveData.toHex().toUpper();
        }
        emit receiveData(m_receiveData);
    });

}

TcpClient::~TcpClient()
{
    //自己销毁
    // m_reconnectTimer->disconnect();
    // m_reconnectTimer->deleteLater();

    // 结束连接
    m_tcpSocket->disconnectFromHost();
    m_tcpSocket->deleteLater() ;
}

void TcpClient::sendData(QByteArray data){
    m_tcpSocket->write(data);
}

void TcpClient::startClientReconnectTcpServerTimer()
{
    qDebug() << "startClientReconnectTcpServerTimer: " << QThread::currentThread();

    //如果不带this，则需要自己销毁
    m_reconnectTimer = new QTimer(this);

    connect(m_reconnectTimer, &QTimer::timeout,
            this, &TcpClient::reConnectTcpServer);

    m_reconnectTimer->start(m_refreshTime);

}


//重新连接服务器
bool TcpClient::reConnectTcpServer()
{
    qDebug() << "reConnectTcpServer: " << QThread::currentThread();

    if(m_tcpSocket->state() != QAbstractSocket::ConnectedState){
        m_tcpSocket->abort();
        m_tcpSocket->connectToHost(m_ip, m_port);

        if(m_tcpSocket->waitForConnected(2000)){
            qDebug() << "成功连接服务器:"<<m_tcpSocket->state();
            m_reconnectTimer->stop();

            return false;
        }
        else{
            qDebug() << "失败连接服务器："<<m_tcpSocket->state();

           m_reconnectTimer->setInterval(0);
            m_reconnectTimer->start(m_refreshTime);
            return true;
        }
    }else{
        return false;
    }
}


int TcpClient::getConnectStatus()
{
    return m_tcpSocket->state();
}




